// src/stores/material.ts
import { defineStore } from 'pinia';
import axios from '@/plugins/axios';

// 物资数据接口
export interface Material {
  id: number;
  materialNumber: string;
  name: string;
  typeId: number;
  typeName: string;
  warehouseId: number;
  warehouseName: string;
  quantity: number;
  status: string;
  createTime: string;
}

// 物资表单字段配置
export const materialFields = [
  {
    key: 'materialNumber',
    label: '物资编号',
    type: 'text',
    placeholder: '请输入物资编号（如 M001）',
    maxLength: 10,
  },
  {
    key: 'name',
    label: '名称',
    type: 'text',
    placeholder: '请输入物资名称',
    maxLength: 50,
  },
  {
    key: 'typeId',
    label: '类型',
    type: 'select',
    placeholder: '请选择物资类型',
    options: [] as { value: number; label: string }[],
  },
  {
    key: 'warehouseId',
    label: '仓库',
    type: 'select',
    placeholder: '请选择仓库',
    options: [] as { value: number; label: string }[],
  },
  {
    key: 'quantity',
    label: '数量',
    type: 'number',
    placeholder: '请输入数量',
  },
  {
    key: 'status',
    label: '状态',
    type: 'select',
    placeholder: '请选择状态',
    options: [] as { value: string; label: string }[],
  },
];

export const useMaterialStore = defineStore('material', {
  state: () => ({
    materials: [] as Material[],
  }),
  actions: {
    // 获取物资列表（无分页）
    async fetchMaterials() {
      try {
        const response = await axios.get('/materials');
        if (response.data.code === 200) {
          this.materials = response.data.data;
          return this.materials;
        }
        throw new Error(response.data.message || '获取物资失败');
      } catch (error) {
        throw new Error('获取物资失败');
      }
    },
    // 创建物资
    async createMaterial(data: { materialNumber: string; name: string; typeId: number; warehouseId: number; quantity: number; status: string }) {
      try {
        const response = await axios.post('/materials', data);
        if (response.data.code === 200) {
          return response.data.data;
        }
        throw new Error(response.data.message || '创建物资失败');
      } catch (error) {
        throw error;
      }
    },
    // 更新物资
    async updateMaterial(data: Material) {
      try {
        const response = await axios.put('/materials', data);
        if (response.data.code === 200) {
          return response.data.data;
        }
        throw new Error(response.data.message || '更新物资失败');
      } catch (error) {
        throw error;
      }
    },
    // 删除物资
    async deleteMaterial(id: number) {
      try {
        const response = await axios.delete(`/materials/${id}`);
        if (response.data.code === 200) {
          return response.data.data;
        }
        throw new Error(response.data.message || '删除物资失败');
      } catch (error) {
        throw error;
      }
    },
  },
});